package files

import (
	"errors"
	"github.com/labstack/gommon/log"
	"io"
	"longmen/server/pkg/common/helper/encrypt"
	"longmen/server/pkg/common/helper/util"
	"mime/multipart"
	"net/http"
	"os"
	"path"
)

type Reader struct {
	io.Reader
	Total   int64
	Current int64
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)

	r.Current += int64(n)
	//fmt.Printf("\r进度 %.2f%%", float64(r.Current*10000/r.Total)/100)

	return
}

func DownloadFileProgress(url string, fileDir, filename string) error {
	_, err := os.Stat(fileDir)
	if os.IsNotExist(err) {
		err := os.MkdirAll(fileDir, 0777)
		if err != nil {
			return err
		}
	}
	filename = fileDir + "/" + filename
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer func() { _ = r.Body.Close() }()

	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer func() { _ = f.Close() }()

	reader := &Reader{
		Reader: r.Body,
		Total:  r.ContentLength,
	}

	_, _ = io.Copy(f, reader)
	return nil
}

func UploadFile(file *multipart.FileHeader, fileDir string) (string, error) {
	if file == nil {
		return "", errors.New("文件信息为空")
	}
	src, err := file.Open()
	if err != nil {
		log.Error("上传文件失败 ", err)
		return "", err
	}
	defer src.Close()
	sizeIt, ok := src.(util.Size)
	if ok {
		log.Info("上传文件大小：", sizeIt.Size())
	}
	_, err = os.Stat(fileDir)
	if os.IsNotExist(err) {
		err := os.MkdirAll(fileDir, 0777)
		if err != nil {
			log.Error("新建文件夹失败 ", err)
			return "", err
		}
	}
	fileSuffix := path.Ext(file.Filename)
	Filename := encrypt.GenHashWithLength(32) + fileSuffix
	f, err := os.OpenFile(path.Join(fileDir, Filename), os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		log.Error("上传文件失败 ", err)
		return "", err
	}
	defer f.Close()

	if _, err = io.Copy(f, src); err != nil {
		log.Error("上传文件失败 ", err)
		return "", err
	}
	return Filename, nil
}
